﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Vit.Mvc.DataAnnotations;

namespace Vit.Mvc
{
    public class ViewModelMetadata : DataAnnotationsModelMetadata
    {
        public ViewModelMetadata(DataAnnotationsModelMetadataProvider provider, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName, DisplayColumnAttribute displayColumnAttribute, IEnumerable<Attribute> attributes)
            : base(provider, containerType, modelAccessor, modelType, propertyName, displayColumnAttribute)
        {
            Attributes = new List<Attribute>(attributes);
            this.IsRequired = Attributes.Any(o => o is RequiredAttribute);

            this.ShowForSearch = Attributes.Any(o => o is SearchAttribute);
            this.ShowForList = Attributes.Any(o => o is ListAttribute);
            this.ShowForDetail = Attributes.Any(o => o is DetailAttribute);
            this.ShowForEdit = Attributes.Any(o => o is EditAttribute);
            this.ShowForDisplay = this.ShowForDetail;
        }

        private IEnumerable<ViewModelMetadata> properties2;
        public IEnumerable<ViewModelMetadata> Properties2
        {
            get
            {
                if (properties2 == null)
                    properties2 = Properties.Cast<ViewModelMetadata>();
                return properties2;
            }
        }

        public bool ShowForSearch { get; set; }
        public bool ShowForList { get; set; }
        public bool ShowForDetail { get; set; }

        public SearchAttribute Search
        {
            get
            {
                return Attributes.OfType<SearchAttribute>().FirstOrDefault();
            }
        }

        public ListAttribute List
        {
            get
            {
                return Attributes.OfType<ListAttribute>().FirstOrDefault();
            }
        }

        public DetailAttribute Detail
        {
            get
            {
                return Attributes.OfType<DetailAttribute>().FirstOrDefault();
            }
        }

        public EditAttribute Edit
        {
            get
            {
                return Attributes.OfType<EditAttribute>().FirstOrDefault();
            }
        }

        public List<Attribute> Attributes
        {
            get;
            private set;
        }
   }
}
